<template>
  <PublicLoading v-if="loading.mounted" />
  <div v-else class="dt-main-tabs-content">
    <div class="dt-content-main">
      <div class="dt-content-head">
        <div class="dt-content-head-tab">
          <span class="dt-head-title">团队成员</span>
        </div>
      </div>
      <div class="dt-content-page" v-if="IsManager == 1 || IsManager == 2">
        <div class="dt-content-em-title">
          <p>{{ team_name }}</p>
          <div class="dt-content-em-btn">
            <el-button class="opr-btn" type="primary" size="mini" v-if="IsManager == 1" @click="addMember(1)">添加成员</el-button>
            <el-button class="opr-btn" type="primary" size="mini" v-if="IsManager == 1" @click="goImport">批量导入</el-button>
          </div>
        </div>
        <div class="dt-content-em-table">
          <el-table
            v-if="tableData.length > 0"
            :data="tableData"
            border
            style="width: 100%"
            :header-cell-style="headerRowStyle"
            :height="tableHeight"
          >
            <el-table-column type="index" label="序号" width="80"> </el-table-column>
            <el-table-column prop="real_name" label="姓名" min-width="240">
              <template slot-scope="scope">
                <span>{{ scope.row.real_name }}</span
                ><span v-if="scope.row.is_admin == 1" style="color: #2f54eb">(管理员)</span>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" min-width="250"> </el-table-column>
            <el-table-column prop="speciality" label="专业" min-width="270"> </el-table-column>
            <el-table-column prop="title" label="职称" min-width="270"> </el-table-column>
            <el-table-column prop="push_ck_state_name" label="加入创客情况" min-width="180"> </el-table-column>
            <el-table-column prop="create_time" label="账号注册时间" min-width="260"> </el-table-column>
            <el-table-column label="操作" min-width="240">
              <template slot-scope="scope">
                <el-button v-if="IsManager == 1" @click="addMember(2, scope.row)" type="text" size="medium">编辑</el-button>
                <el-button v-if="IsManager == 1 && scope.row.is_admin != 1" type="text" size="medium" @click="deleteMember(scope.row)"
                  >删除</el-button
                >
                <el-button
                  v-if="IsManager == 2 && scope.row.is_admin == 0 && Uid == scope.row.user_id"
                  @click="quitTeam(scope.row)"
                  type="text"
                  size="medium"
                  >退出</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <div class="dt-content-project-list-page">
            <el-pagination
              v-if="tableData.length != 0"
              @current-change="handleCurrentChange"
              :current-page.sync="page"
              :page-size="20"
              layout="prev, pager, next, jumper"
              :total="total_record"
            >
            </el-pagination>
          </div>
        </div>
      </div>
      <div class="dt-content-em-table-empty" v-if="IsManager == 0">
        <div class="dt-empty"><img src="/skb/img/ic_wrz110.png" alt="" /></div>
        <div>您尚未完成身份认证，请完成后再创建团队。</div>
        <div><el-button type="primary" @click="goAuthentication">立即认证</el-button></div>
      </div>
      <div class="dt-content-em-table-creatteam" v-if="IsManager == 3">
        <div class="dt-empty"><img src="/skb/img/ic_td474.png" alt="" /></div>
        <div>团队名称</div>
        <div><el-input v-model.trim="teamName" placeholder="请输入团队名称" size="medium" :maxlength="20"></el-input></div>
        <div><el-button type="primary" style="width: 106px" @click="createTeam" :loading="createLock">创建团队</el-button></div>
      </div>
    </div>

    <el-dialog
      :title="openType == 1 ? '添加成员' : '编辑成员'"
      :visible.sync="IsAddMember"
      width="30%"
      :before-close="closeAddMember"
      :append-to-body="true"
      :close-on-click-modal="false"
      class="dt-content-em-table-add"
    >
      <el-form :model="memberForm" :rules="rules" ref="memberForm" label-width="100px" class="demo-ruleForm" label-position="left">
        <el-form-item label="姓名" prop="real_name">
          <el-input
            v-model.trim="memberForm.real_name"
            placeholder="请输入员工真实姓名（2 -4 个汉字）"
            :disabled="openType == 2"
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model.trim="memberForm.phone"
            placeholder="请输入员工真实手机号"
            :disabled="openType == 2"
            maxlength="11"
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model.trim="memberForm.id_card" placeholder="请输入员工身份证号" :disabled="openType == 2" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="speciality">
          <el-input
            type="textarea"
            v-model.trim="memberForm.speciality"
            maxlength="20"
            show-word-limit
            placeholder="请输入专业名称"
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input type="textarea" v-model.trim="memberForm.title" maxlength="20" show-word-limit placeholder="请输入职称" size="medium"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="footer-btn" type="primary" @click="SureAddMember('memberForm')" :loading="addMemberLock">{{
          openType == 1 ? '添加' : '保存'
        }}</el-button>
        <el-button class="footer-btn" style="color: #1f1f1f" @click="closeAddMember('memberForm')">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 自定义验证手机号码的函数
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号码不能为空'))
      }
      // 更严格的手机号码验证可以使用正则表达式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    // 自定义验证身份证号的函数
    var validateIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('身份证号不能为空'))
      }
      // 身份证号的正则表达式（简单的验证，可根据需求调整）
      const idCardRegex = /^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
      if (!idCardRegex.test(value)) {
        callback(new Error('请输入正确的身份证号'))
      } else {
        callback()
      }
    }
    return {
      tableHeight: 841,
      loading: { mounted: true },
      page: 1,
      tableData: [],
      Uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id,
      // IsManager: this.$store.state.manager,
      IsManager: 1,
      total_page: 0,
      total_record: 0,
      IsAddMember: false,
      openType: 1,
      memberForm: {
        real_name: '',
        phone: '',
        id_card: '',
        speciality: '',
        title: ''
      },
      rules: {
        real_name: [
          { required: true, message: '请输入用户实名', trigger: 'blur' },
          { min: 2, max: 4, message: '长度在 2 到 4 个汉字', trigger: 'blur' }
        ],
        phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        id_card: [{ required: true, validator: validateIdCard, trigger: 'blur' }],
        speciality: [{ message: '请输入专业', trigger: 'blur' }],
        title: [{ message: '请输入职称', trigger: 'blur' }]
      },
      id: 0,
      team_name: '',
      addMemberLock: false,
      teamName: '',
      createLock: false
    }
  },
  methods: {
    headerRowStyle() {
      return {
        'font-size': '14px', // 设置表头字体大小
        'background-color': '#fafafa', // 设置表头背景色
        'font-weight': 'bold', // 设置表头字体加粗
        color: '#909399' // 设置表头字体颜色
      }
    },
    handleCurrentChange(page) {
      this.page = page
      this.getMemberList()
    },
    getMemberList() {
      var data = [
          {
            user_id: this.Uid,
            page: this.page,
            page_size: 20
          }
        ],
        domain = [this.$store.state.HOST],
        path = ['/EnterpriseMember/enterprise_member_list'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            console.log(data)
            if (data.code === 200) {
              this.loading.mounted = false

              this.tableData = data.data.items
              this.total_page = data.data.total_page
              this.total_record = data.data.total_record
              this.team_name = data.data.team_name

              this.getTableHeight()
            }
          })
        })
        .catch((error) => {})
    },
    addMember(openType, row) {
      this.openType = openType
      if (openType == 1) {
        this.IsAddMember = true
      } else {
        this.id = row.id
        var data = [
            {
              id: row.id
            }
          ],
          domain = [this.$store.state.HOST],
          path = ['/EnterpriseMember/enterprise_member_info'],
          dataAxios = this.$tools.getDataAxios(this, domain, path, data)
        Promise.all(dataAxios)
          .then((response) => {
            this.$tools.callbackAxios(this, response, (response) => {
              var data = response[0].data
              if (data.code === 200) {
                data.data.id_card = this.$tools.getDecrypt(data.data.id_card)
                this.memberForm = data.data
                this.IsAddMember = true
              }
            })
          })
          .catch((error) => {})
      }
    },
    SureAddMember(formName) {
      if (this.addMemberLock) return

      if (this.openType == 1) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addMemberLock = true
            var data = [
                {
                  user_id: this.Uid,
                  real_name: this.memberForm.real_name,
                  phone: this.memberForm.phone,
                  id_card: this.memberForm.id_card,
                  speciality: this.memberForm.speciality,
                  title: this.memberForm.title
                }
              ],
              domain = [this.$store.state.HOST],
              path = ['/EnterpriseMember/enterprise_member_add'],
              dataAxios = this.$tools.getDataAxios(this, domain, path, data)
            Promise.all(dataAxios)
              .then((response) => {
                this.$tools.callbackAxios(this, response, (response) => {
                  var data = response[0].data
                  if (data.code === 200) {
                    this.$message({
                      message: data.message,
                      type: 'success',
                      duration: 2000,
                      onClose: () => {
                        this.addMemberLock = false
                      }
                    })

                    this.IsAddMember = false
                    this.getMemberList()
                    this.closeCallback()
                  } else {
                    this.$message({
                      message: data.message,
                      type: 'warning',
                      duration: 2000,
                      onClose: () => {
                        this.addMemberLock = false
                      }
                    })
                  }
                })
              })
              .catch((error) => {})
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.addMemberLock = true
        var data = [
            {
              id: this.id,
              user_id: this.Uid,
              speciality: this.memberForm.speciality,
              title: this.memberForm.title
            }
          ],
          domain = [this.$store.state.HOST],
          path = ['/EnterpriseMember/enterprise_member_edit'],
          dataAxios = this.$tools.getDataAxios(this, domain, path, data)
        Promise.all(dataAxios)
          .then((response) => {
            this.$tools.callbackAxios(this, response, (response) => {
              var data = response[0].data
              if (data.code === 200) {
                this.$message({
                  message: data.message,
                  type: 'success',
                  duration: 2000,
                  onClose: () => {
                    this.addMemberLock = false
                  }
                })
                this.IsAddMember = false
                this.getMemberList()
                this.closeCallback()
              } else {
                this.$message({
                  message: data.message,
                  type: 'warning',
                  duration: 2000,
                  onClose: () => {
                    this.addMemberLock = false
                  }
                })
              }
            })
          })
          .catch((error) => {})
      }
    },
    closeAddMember() {
      this.IsAddMember = false
      this.addMemberLock = false
      this.$refs['memberForm'].resetFields()
      this.closeCallback()
    },
    closeCallback() {
      this.memberForm = {
        real_name: '',
        phone: '',
        id_card: '',
        speciality: '',
        title: ''
      }
    },
    deleteMember(row) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('div', { class: 'dt-content-em-delete-content' }, [
          h('p', null, [h('span', null, [h('i', { class: 'el-icon-warning' }), h('em', null, '确定删除该成员吗？')])]),
          h('p', null, [h('span', null, ['删除后该用户将脱离团队，不影响用户账号使用。'])])
        ]),

        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'dt-button-cancle is-plain',
        // beforeClose: (action, instance, done) => {
        //   if (action === 'confirm') {
        //     instance.confirmButtonLoading = true
        //     instance.confirmButtonText = '执行中...'
        //     setTimeout(() => {
        //       done()
        //       setTimeout(() => {
        //         instance.confirmButtonLoading = false
        //       }, 300)
        //     }, 3000)
        //   } else {
        //     done()
        //   }
        // },
        customClass: 'dt-content-em-delete'
      }).then(() => {
        var data = [
            {
              id: row.id
            }
          ],
          domain = [this.$store.state.HOST],
          path = ['/EnterpriseMember/enterprise_member_delete'],
          dataAxios = this.$tools.getDataAxios(this, domain, path, data)
        Promise.all(dataAxios)
          .then((response) => {
            this.$tools.callbackAxios(this, response, (response) => {
              var data = response[0].data
              if (data.code === 200) {
                this.getMemberList()

                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              }
            })
          })
          .catch((error) => {})
        // this.$message({
        //   type: 'info',
        //   message: 'action: ' + action
        // }).catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '取消'
        //   })
        // })
      })
      // this.$confirm('删除后该用户将脱离团队成员，不影响员工账号使用', '确定删除该员工吗?', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     var data = [
      //         {
      //           id: row.id
      //         }
      //       ],
      //       domain = [this.$store.state.HOST],
      //       path = ['/EnterpriseMember/enterprise_member_delete'],
      //       dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      //     Promise.all(dataAxios)
      //       .then((response) => {
      //         this.$tools.callbackAxios(this, response, (response) => {
      //           var data = response[0].data
      //           if (data.code === 200) {
      //             this.getMemberList()
      //             this.$message({
      //               type: 'success',
      //               message: '删除成功!'
      //             })
      //           }
      //         })
      //       })
      //       .catch((error) => {})
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消删除'
      //     })
      //   })
    },
    quitTeam(row) {
      this.$confirm('确定退出团队吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'dt-button-cancle is-plain',
        // iconClass: '',
        type: 'warning',
        customClass: 'dt-chat-content-link-confirm'
      })
        .then(() => {
          var data = [{ id: row.id }],
            domain = [this.$store.state.HOST],
            path = ['/EnterpriseMember/enterprise_member_exit'],
            dataAxios = this.$tools.getDataAxios(this, domain, path, data)
          Promise.all(dataAxios)
            .then((response) => {
              this.$tools.callbackAxios(this, response, (response) => {
                var data = response[0].data
                if (data.code === 200) {
                  this.getUserInfo()
                } else {
                  this.$message({
                    message: data.message,
                    type: 'warning',
                    onClose: () => {}
                  })
                }
              })
            })
            .catch((error) => {})
        })
        .catch(() => {})
    },
    goAuthentication() {
      let detailUrl = 'https://www.ccccdt.com/myAccountauthEnterprise'
      window.open(detailUrl, '_blank')
    },
    getUserInfo() {
      var data = [{ user_id: this.Uid }],
        domain = [this.$store.state.USER_DOMAIN],
        path = ['/phoneapi/get_user_info_2019'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.IsManager = data.data.is_team_member
              if (data.data.is_team_member == 1 || data.data.is_team_member == 2) {
                this.getMemberList()
              }
              this.loading.mounted = false
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    createTeam() {
      this.createLock = true
      if (this.teamName == '') {
        this.$message({
          message: '请输入团队名称',
          type: 'warning',
          duration: 1500,
          onClose: () => {
            this.createLock = false
          }
        })
        return
      }
      var data = [{ user_id: this.Uid, team_name: this.teamName }],
        domain = [this.$store.state.HOST],
        path = ['/EnterpriseMember/team_add'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.createLock = false
              this.IsManager = 1
              this.getMemberList()
              this.$message({
                message: '操作成功',
                type: 'success',
                onClose: () => {}
              })
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {
                  this.createLock = false
                }
              })
            }
          })
        })
        .catch((error) => {})
    },
    goImport() {
      this.$router.push('/main/#/em?tab=import')
    },
    getTableHeight() {
      this.tableHeight = 0
      var th = 0
      if (this.tableData.length) th = 40 * this.tableData.length + 41
      this.$nextTick(() => {
        setTimeout(() => {
          if (!this.tableData.length) return
          const contentHeight = document.querySelector('.dt-content-em-table').clientHeight
          const headerHeight = document.querySelector('.dt-content-em-table .el-table__header-wrapper').clientHeight

          var ttHeight = contentHeight - headerHeight - 40
          if (th < ttHeight && th > 0) this.tableHeight = th
          else this.tableHeight = ttHeight
        }, 100)
      })
    }
  },

  mounted() {
    window.addEventListener('resize', this.getTableHeight)

    this.getUserInfo()
  }
}
</script>
<style scoped>
.dt-content-page {
  margin: 0;
  background-color: #f2f3f5;
  padding: 16px;
}
.dt-content-em-title {
  display: flex;
  justify-content: space-between;
}
.dt-content-em-title > p {
  font-size: 20px;
  color: #1f1f1f;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.opr-btn {
  width: 78px;
  height: 28px;
  padding: 0 !important;
}
.dt-content-em-table {
  /* margin: 16px; */
  margin-top: 16px;
  padding: 14px 14px 0 14px;
  background-color: #fff;
  flex: 1;
}
/* 全局样式中设置行高 */
.dt-content-em-table >>> .el-table .el-table__row {
  height: 40px;
}

.dt-content-project-list-page {
  display: flex;
  justify-content: center;
  padding: 40px 0 20px 0;
}
.dt-content-project-list-page {
  position: absolute;
  bottom: 14px;
  left: 50%;
  transform: translateX(-50%);
}
.dt-content-em-table >>> .el-table th.el-table__cell {
  padding: 0;
  height: 40px;
  color: '#909399';
}
.dt-content-em-table >>> .el-table .el-table__cell {
  padding: 0;
  color: #1f1f1f;
}
.dt-content-em-table >>> .el-button--medium {
  padding: 8px 0px;
}
.dt-content-em-table-empty {
  flex: 1;
  text-align: center;
  padding-top: 212px;
  background: #ffffff;
  margin: 16px;
}
.dt-content-em-table-empty > div:nth-of-type(1) {
  margin-bottom: 20px;
}
.dt-content-em-table-empty > div:nth-of-type(2) {
  margin-bottom: 30px;
  font-size: 16px;
  color: #1f1f1f;
  /* line-height: 48px; */
}
.dt-content-em-table-creatteam {
  flex: 1;
  background: #ffffff;
  margin: 16px;
  text-align: center;
  padding-top: 140px;
}
.dt-content-em-table-creatteam > div:nth-of-type(1) {
  margin-bottom: 40px;
}
.dt-content-em-table-creatteam > div:nth-of-type(2) {
  color: #1f1f1f;
  font-size: 18px;
  text-align: center;
  margin-bottom: 20px;
}
.dt-content-em-table-creatteam > div:nth-of-type(3) {
  width: 540px;
  margin: 0 auto 40px auto;
}
.dt-content-em-table-add >>> .el-dialog__footer {
  box-shadow: 0px 1px 0px #e9eef7 inset;
  padding: 12px !important;
  padding-right: 20px !important;
}
.dt-content-em-table-add >>> .el-dialog__body {
  padding: 6px 20px 0 20px;
}
.footer-btn {
  width: 78px;
  height: 36px;
  padding: 0 !important;
}
</style>
